<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网盘资源共享社区</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #2388ff;
            --secondary-color: #2ea043;
            --background-color: #f6f8fa;
            --sidebar-bg: #ffffff;
            --text-color: #24292f;
            --border-color: #d0d7de;
            --hover-color: #f6f8fa;
            --message-incoming: #ffffff;
            --message-outgoing: #ddf4ff;
            --success-color: #2ea043;
            --warning-color: #d4a72c;
            --danger-color: #cf222e;
        }

        [data-theme="dark"] {
            --primary-color: #388bfd;
            --secondary-color: #3fb950;
            --background-color: #0d1117;
            --sidebar-bg: #161b22;
            --text-color: #f0f6fc;
            --border-color: #30363d;
            --hover-color: #161b22;
            --message-incoming: #21262d;
            --message-outgoing: #0c2d6b;
            --success-color: #3fb950;
            --warning-color: #d29922;
            --danger-color: #f85149;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
        }

        body {
            display: flex;
            height: 100vh;
            background-color: var(--background-color);
            color: var(--text-color);
        }

        /* 左侧边栏样式 */
        .sidebar {
            width: 350px;
            background-color: var(--sidebar-bg);
            border-right: 1px solid var(--border-color);
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            transition: all 0.3s ease;
        }

        .user-header {
            padding: 15px;
            background-color: var(--sidebar-bg);
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .user-info {
            display: flex;
            align-items: center;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 12px;
        }

        .user-name {
            font-weight: 600;
        }

        .theme-toggle {
            background: none;
            border: none;
            color: var(--text-color);
            cursor: pointer;
            font-size: 18px;
        }

        .search-container {
            padding: 15px;
            background-color: var(--sidebar-bg);
            border-bottom: 1px solid var(--border-color);
            position: relative;
        }

        .search-bar {
            display: flex;
            align-items: center;
            background-color: var(--background-color);
            border-radius: 6px;
            padding: 8px 15px;
            border: 1px solid var(--border-color);
        }

        .search-bar i {
            color: var(--text-color);
            margin-right: 8px;
            opacity: 0.7;
        }

        .search-bar input {
            width: 100%;
            padding: 5px 0;
            border: none;
            background: transparent;
            font-size: 14px;
            outline: none;
            color: var(--text-color);
        }

        .groups-list {
            overflow-y: auto;
            flex: 1;
        }

        .group-item {
            display: flex;
            padding: 15px;
            border-bottom: 1px solid var(--border-color);
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .group-item.active {
            background-color: var(--hover-color);
        }

        .group-item:hover {
            background-color: var(--hover-color);
        }

        .group-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            font-weight: bold;
            margin-right: 15px;
            flex-shrink: 0;
        }

        .group-info {
            flex: 1;
            min-width: 0;
        }

        .group-name {
            font-weight: 600;
            margin-bottom: 5px;
            display: flex;
            justify-content: space-between;
        }

        .group-last-message {
            color: var(--text-color);
            opacity: 0.7;
            font-size: 14px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .group-time {
            color: var(--text-color);
            opacity: 0.6;
            font-size: 12px;
            flex-shrink: 0;
        }

        .unread-count {
            background-color: var(--primary-color);
            color: white;
            border-radius: 12px;
            min-width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            margin-left: 8px;
            padding: 0 6px;
        }

        .create-group-btn {
            margin: 15px;
            padding: 12px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        /* 右侧聊天区域样式 */
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: var(--background-color);
        }

        .chat-header {
            padding: 15px;
            background-color: var(--sidebar-bg);
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .chat-info {
            display: flex;
            align-items: center;
        }

        .chat-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            font-weight: bold;
            margin-right: 15px;
            flex-shrink: 0;
        }

        .chat-details {
            display: flex;
            flex-direction: column;
        }

        .chat-name {
            font-weight: 600;
        }

        .chat-members {
            font-size: 13px;
            opacity: 0.7;
        }

        .chat-actions {
            display: flex;
            gap: 10px;
        }

        .chat-action-btn {
            background: none;
            border: none;
            color: var(--text-color);
            cursor: pointer;
            font-size: 16px;
            opacity: 0.7;
            transition: opacity 0.2s;
        }

        .chat-action-btn:hover {
            opacity: 1;
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .message {
            display: flex;
            flex-direction: column;
            max-width: 80%;
        }

        .message-content {
            padding: 12px 16px;
            border-radius: 12px;
            position: relative;
            word-break: break-word;
        }

        .message-time {
            font-size: 11px;
            opacity: 0.6;
            margin-top: 5px;
        }

        .message-incoming {
            align-items: flex-start;
        }

        .message-incoming .message-content {
            background-color: var(--message-incoming);
            border-top-left-radius: 0;
            border: 1px solid var(--border-color);
        }

        .message-outgoing {
            align-items: flex-end;
            align-self: flex-end;
        }

        .message-outgoing .message-content {
            background-color: var(--message-outgoing);
            border-top-right-radius: 0;
        }

        .resource-card {
            margin-top: 8px;
            padding: 12px;
            border-radius: 8px;
            background-color: var(--background-color);
            border: 1px solid var(--border-color);
        }

        .resource-header {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }

        .resource-icon {
            margin-right: 8px;
            font-size: 16px;
        }

        .resource-title {
            font-weight: 600;
            font-size: 14px;
        }

        .resource-description {
            font-size: 13px;
            opacity: 0.8;
            margin-bottom: 8px;
            line-height: 1.4;
        }

        .resource-link {
            display: inline-block;
            padding: 6px 12px;
            background-color: var(--primary-color);
            color: white;
            text-decoration: none;
            border-radius: 4px;
            font-size: 13px;
        }

        .resource-status {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            margin-left: 8px;
        }

        .status-pending {
            background-color: var(--warning-color);
            color: black;
        }

        .status-approved {
            background-color: var(--success-color);
            color: white;
        }

        .status-rejected {
            background-color: var(--danger-color);
            color: white;
        }

        .no-chat-selected {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: var(--text-color);
            opacity: 0.5;
            text-align: center;
            padding: 20px;
        }

        .no-chat-selected i {
            font-size: 48px;
            margin-bottom: 20px;
        }

        .chat-input-container {
            padding: 15px;
            background-color: var(--sidebar-bg);
            border-top: 1px solid var(--border-color);
            display: flex;
            align-items: center;
        }

        .chat-input {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background-color: var(--background-color);
            font-size: 14px;
            outline: none;
            color: var(--text-color);
        }

        .send-button {
            margin-left: 10px;
            width: 40px;
            height: 40px;
            border-radius: 6px;
            background-color: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border: none;
            outline: none;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal-content {
            background-color: var(--sidebar-bg);
            padding: 24px;
            border-radius: 12px;
            width: 400px;
            max-width: 90%;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }

        .modal-header {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-title {
            font-weight: 600;
            font-size: 18px;
            color: var(--text-color);
        }

        .close-modal {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: var(--text-color);
        }

        .form-group {
            margin-bottom: 16px;
        }

        .form-label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            color: var(--text-color);
        }

        .form-input {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background-color: var(--background-color);
            color: var(--text-color);
            font-size: 14px;
        }

        .form-select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background-color: var(--background-color);
            color: var(--text-color);
            font-size: 14px;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .btn {
            padding: 10px 16px;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            border: none;
            font-size: 14px;
            transition: all 0.2s;
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            opacity: 0.9;
        }

        .btn-secondary {
            background-color: var(--background-color);
            color: var(--text-color);
            border: 1px solid var(--border-color);
        }

        .btn-secondary:hover {
            background-color: var(--hover-color);
        }

        /* 搜索样式 */
        .search-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: var(--sidebar-bg);
            border-radius: 0 0 6px 6px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            max-height: 300px;
            overflow-y: auto;
            z-index: 100;
            display: none;
            border: 1px solid var(--border-color);
            border-top: none;
        }

        .search-result-item {
            padding: 12px 15px;
            cursor: pointer;
            display: flex;
            align-items: center;
            border-bottom: 1px solid var(--border-color);
        }

        .search-result-item:hover {
            background-color: var(--hover-color);
        }

        .search-result-item i {
            margin-right: 10px;
            color: var(--primary-color);
        }

        .empty-state {
            padding: 20px;
            text-align: center;
            color: var(--text-color);
            opacity: 0.7;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: absolute;
                z-index: 100;
                left: -100%;
            }

            .sidebar.active {
                left: 0;
            }

            .mobile-menu-btn {
                display: block;
                position: absolute;
                top: 15px;
                left: 15px;
                z-index: 101;
                background: var(--primary-color);
                color: white;
                border: none;
                border-radius: 4px;
                padding: 8px 12px;
                cursor: pointer;
            }
        }

        /* 加载指示器 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, .3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* 加入群组按钮 */
        .join-group-btn {
            padding: 6px 12px;
            background-color: var(--success-color);
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            margin-left: 10px;
        }

        /* 资源搜索结果样式 */
        .search-resource-item {
            display: flex;
            flex-direction: column;
            padding: 10px;
            border-bottom: 1px solid var(--border-color);
        }

        .search-resource-title {
            font-weight: 600;
            margin-bottom: 5px;
        }

        .search-resource-content {
            font-size: 13px;
            opacity: 0.8;
            margin-bottom: 5px;
            word-break: break-all;
        }

        .search-resource-group {
            font-size: 12px;
            opacity: 0.6;
        }
    </style>
</head>

<body>
    <!-- 移动端菜单按钮 -->
    <button class="mobile-menu-btn" id="mobile-menu-btn" style="display: none;">
        <i class="fas fa-bars"></i>
    </button>

    <!-- 左侧边栏 -->
    <div class="sidebar" id="sidebar">
        <div class="user-header">
            <div class="user-info">
                <div class="user-avatar" id="user-avatar">U</div>
                <div class="user-name" id="user-name">未登录</div>
            </div>
            <button class="theme-toggle" id="theme-toggle">
                <i class="fas fa-moon"></i>
            </button>
        </div>

        <div class="search-container">
            <div class="search-bar">
                <i class="fas fa-search"></i>
                <input type="text" id="search-input" placeholder="搜索群组或资源...">
            </div>
            <div class="search-results" id="search-results">
                <!-- 搜索结果将在这里显示 -->
            </div>
        </div>

        <div class="groups-list" id="groups-list">
            <!-- 群组列表将通过JS生成 -->
        </div>

        <button class="create-group-btn" id="create-group-btn">
            <i class="fas fa-plus"></i> 创建新群组
        </button>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-container">
        <div class="chat-header" id="chat-header">
            <div class="chat-info">
                <div class="chat-avatar" id="current-chat-avatar">G</div>
                <div class="chat-details">
                    <div class="chat-name" id="current-chat-name">网盘资源共享社区</div>
                    <div class="chat-members" id="current-chat-members">选择一个群组开始聊天</div>
                </div>
            </div>
            <div class="chat-actions">
                <button class="chat-action-btn" id="share-resource-btn" title="分享资源" style="display: none;">
                    <i class="fas fa-link"></i>
                </button>
                <button class="chat-action-btn" id="group-info-btn" title="群组信息" style="display: none;">
                    <i class="fas fa-info-circle"></i>
                </button>
                <button class="chat-action-btn" id="leave-group-btn" title="退出群组" style="display: none;">
                    <i class="fas fa-sign-out-alt"></i>
                </button>
            </div>
        </div>

        <div class="chat-messages" id="chat-messages">
            <div class="no-chat-selected" id="no-chat-selected">
                <i class="fas fa-users"></i>
                <h3>欢迎使用网盘资源共享社区</h3>
                <p>请从左侧选择一个群组或创建新群组开始分享资源</p>
            </div>
        </div>

        <div class="chat-input-container">
            <input type="text" id="message-input" class="chat-input" placeholder="输入消息或输入 /搜索 来查找资源..." disabled>
            <button class="send-button" id="send-button" disabled>
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
    </div>

    <!-- 登录模态框 -->
    <div class="modal" id="login-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">用户登录</h2>
                <button class="close-modal">&times;</button>
            </div>
            <div class="form-group">
                <label class="form-label">用户名</label>
                <input type="text" class="form-input" id="login-username" placeholder="请输入用户名">
            </div>
            <div class="form-group">
                <label class="form-label">密码</label>
                <input type="password" class="form-input" id="login-password" placeholder="请输入密码">
            </div>
            <div class="form-actions">
                <button class="btn btn-secondary" id="show-register-btn">注册新账户</button>
                <button class="btn btn-primary" id="do-login-btn">登录</button>
            </div>
        </div>
    </div>

    <!-- 注册模态框 -->
    <div class="modal" id="register-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">用户注册</h2>
                <button class="close-modal">&times;</button>
            </div>
            <div class="form-group">
                <label class="form-label">用户名</label>
                <input type="text" class="form-input" id="register-username" placeholder="请输入用户名">
            </div>
            <div class="form-group">
                <label class="form-label">密码</label>
                <input type="password" class="form-input" id="register-password" placeholder="请输入密码">
            </div>
            <div class="form-group">
                <label class="form-label">确认密码</label>
                <input type="password" class="form-input" id="register-password-confirm" placeholder="请再次输入密码">
            </div>
            <div class="form-actions">
                <button class="btn btn-secondary" id="show-login-btn">返回登录</button>
                <button class="btn btn-primary" id="do-register-btn">注册</button>
            </div>
        </div>
    </div>

    <!-- 创建群组模态框 -->
    <div class="modal" id="create-group-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">创建新群组</h2>
                <button class="close-modal">&times;</button>
            </div>
            <div class="form-group">
                <label class="form-label">群组名称</label>
                <input type="text" class="form-input" id="group-name" placeholder="请输入群组名称">
            </div>
            <div class="form-group">
                <label class="form-label">群组描述</label>
                <textarea class="form-input" id="group-description" placeholder="请输入群组描述"></textarea>
            </div>
            <div class="form-actions">
                <button class="btn btn-secondary" id="cancel-create-group">取消</button>
                <button class="btn btn-primary" id="do-create-group">创建</button>
            </div>
        </div>
    </div>

    <!-- 分享资源模态框 -->
    <div class="modal" id="share-resource-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">分享资源</h2>
                <button class="close-modal">&times;</button>
            </div>
            <div class="form-group">
                <label class="form-label">资源类型</label>
                <select class="form-select" id="resource-type">
                    <option value="baidu">百度网盘</option>
                    <option value="ali">阿里云盘</option>
                    <option value="other">其他网盘</option>
                    <option value="text">文字</option>
                    <option value="image">图片</option>
                    <option value="audio">音频</option>
                    <option value="video">视频</option>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">资源链接/内容</label>
                <textarea class="form-input" id="resource-content" placeholder="请输入资源链接或内容"></textarea>
            </div>
            <div class="form-group">
                <label class="form-label">资源描述</label>
                <textarea class="form-input" id="resource-description" placeholder="请输入资源描述"></textarea>
            </div>
            <div class="form-actions">
                <button class="btn btn-secondary" id="cancel-share-resource">取消</button>
                <button class="btn btn-primary" id="do-share-resource">分享</button>
            </div>
        </div>
    </div>

    <!-- 群组信息模态框 -->
    <div class="modal" id="group-info-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="group-info-title">群组信息</h2>
                <button class="close-modal">&times;</button>
            </div>
            <div class="form-group">
                <label class="form-label">群组名称</label>
                <div class="form-input" id="info-group-name"
                    style="background-color: transparent; border: none; padding: 10px 0;"></div>
            </div>
            <div class="form-group">
                <label class="form-label">群组描述</label>
                <div class="form-input" id="info-group-description"
                    style="background-color: transparent; border: none; padding: 10px 0;"></div>
            </div>
            <div class="form-group">
                <label class="form-label">创建者</label>
                <div class="form-input" id="info-group-creator"
                    style="background-color: transparent; border: none; padding: 10px 0;"></div>
            </div>
            <div class="form-group">
                <label class="form-label">成员列表</label>
                <div class="form-input" id="info-group-members"
                    style="background-color: transparent; border: none; padding: 10px 0; max-height: 150px; overflow-y: auto;">
                </div>
            </div>
            <div class="form-actions">
                <button class="btn btn-secondary" id="close-group-info">关闭</button>
            </div>
        </div>
    </div>

    <script>
        // 应用状态
        let state = {
            currentUser: null,
            currentGroupId: null,
            groups: [],
            messages: {},
            searchResults: [],
            users: [
                { username: "admin", password: "admin123", isAdmin: true },
                { username: "user1", password: "user1123", isAdmin: false },
                { username: "user2", password: "user2123", isAdmin: false }
            ]
        };

        // DOM 元素
        const userAvatar = document.getElementById('user-avatar');
        const userName = document.getElementById('user-name');
        const themeToggle = document.getElementById('theme-toggle');
        const searchInput = document.getElementById('search-input');
        const searchResults = document.getElementById('search-results');
        const groupsList = document.getElementById('groups-list');
        const createGroupBtn = document.getElementById('create-group-btn');
        const currentChatAvatar = document.getElementById('current-chat-avatar');
        const currentChatName = document.getElementById('current-chat-name');
        const currentChatMembers = document.getElementById('current-chat-members');
        const shareResourceBtn = document.getElementById('share-resource-btn');
        const groupInfoBtn = document.getElementById('group-info-btn');
        const leaveGroupBtn = document.getElementById('leave-group-btn');
        const chatMessages = document.getElementById('chat-messages');
        const noChatSelected = document.getElementById('no-chat-selected');
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-button');
        const mobileMenuBtn = document.getElementById('mobile-menu-btn');
        const sidebar = document.getElementById('sidebar');

        // 模态框元素
        const loginModal = document.getElementById('login-modal');
        const registerModal = document.getElementById('register-modal');
        const createGroupModal = document.getElementById('create-group-modal');
        const shareResourceModal = document.getElementById('share-resource-modal');
        const groupInfoModal = document.getElementById('group-info-modal');

        // 初始化应用
        function initApp() {
            loadData();
            checkAuthentication();
            setupEventListeners();
            checkMobileView();

            // 监听窗口大小变化
            window.addEventListener('resize', checkMobileView);
        }

        // 检查是否为移动端视图
        function checkMobileView() {
            if (window.innerWidth <= 768) {
                mobileMenuBtn.style.display = 'block';
                sidebar.style.left = '-100%';
            } else {
                mobileMenuBtn.style.display = 'none';
                sidebar.style.left = '0';
            }
        }

        // 从localStorage加载数据
        function loadData() {
            const savedData = localStorage.getItem('resource-share-data');

            if (savedData) {
                const parsedData = JSON.parse(savedData);
                state.groups = parsedData.groups || [];
                state.messages = parsedData.messages || {};

                // 加载用户数据
                const savedUsers = localStorage.getItem('resource-share-users');
                if (savedUsers) {
                    state.users = JSON.parse(savedUsers);
                }
            } else {
                // 初始示例数据
                state.groups = [
                    {
                        id: 1,
                        name: "前端开发资源",
                        avatar: "F",
                        description: "分享前端开发相关资源",
                        creator: "admin",
                        members: ["admin", "user1"],
                        lastMessage: "最新的React教程已分享",
                        lastMessageTime: "14:20",
                        unreadCount: 0
                    },
                    {
                        id: 2,
                        name: "设计素材库",
                        avatar: "D",
                        description: "UI/UX设计素材分享",
                        creator: "admin",
                        members: ["admin", "user2"],
                        lastMessage: "阿里云盘设计资源链接已发布",
                        lastMessageTime: "昨天",
                        unreadCount: 3
                    },
                    {
                        id: 3,
                        name: "学习资料交流",
                        avatar: "S",
                        description: "各类学习资料分享",
                        creator: "user1",
                        members: ["admin", "user1", "user2"],
                        lastMessage: "等待审核的网盘资源",
                        lastMessageTime: "周三",
                        unreadCount: 0
                    }
                ];

                state.messages = {
                    1: [
                        {
                            id: 1,
                            sender: "admin",
                            content: "欢迎大家加入前端开发资源群！",
                            time: "10:20",
                            type: "text"
                        },
                        {
                            id: 2,
                            sender: "admin",
                            content: "https://pan.baidu.com/s/example123",
                            description: "React高级教程2023",
                            time: "14:15",
                            type: "baidu",
                            status: "approved"
                        },
                        {
                            id: 3,
                            sender: "system",
                            content: "资源已通过审核",
                            time: "14:18",
                            type: "system"
                        }
                    ],
                    2: [
                        {
                            id: 1,
                            sender: "admin",
                            content: "大家好，这里是设计素材分享区",
                            time: "09:30",
                            type: "text"
                        },
                        {
                            id: 2,
                            sender: "admin",
                            content: "https://www.aliyundrive.com/s/example456",
                            description: "UI设计素材合集",
                            time: "13:45",
                            type: "ali",
                            status: "approved"
                        }
                    ],
                    3: [
                        {
                            id: 1,
                            sender: "user1",
                            content: "https://pan.baidu.com/s/example789",
                            description: "编程学习资料打包",
                            time: "11:20",
                            type: "baidu",
                            status: "pending"
                        },
                        {
                            id: 2,
                            sender: "system",
                            content: "资源等待管理员审核",
                            time: "11:21",
                            type: "system"
                        }
                    ]
                };

                saveData();
            }
        }

        // 保存数据到localStorage
        function saveData() {
            localStorage.setItem('resource-share-data', JSON.stringify({
                groups: state.groups,
                messages: state.messages
            }));

            localStorage.setItem('resource-share-users', JSON.stringify(state.users));
        }

        // 检查用户认证状态
        function checkAuthentication() {
            const currentUser = localStorage.getItem('current-user');

            if (currentUser) {
                state.currentUser = JSON.parse(currentUser);
                updateUserInterface();
                renderGroupsList();
            } else {
                showLoginModal();
            }
        }

        // 更新用户界面
        function updateUserInterface() {
            if (state.currentUser) {
                userAvatar.textContent = state.currentUser.username.charAt(0).toUpperCase();
                userName.textContent = state.currentUser.username;
                createGroupBtn.style.display = 'block';
            } else {
                userAvatar.textContent = 'U';
                userName.textContent = '未登录';
                createGroupBtn.style.display = 'none';
            }
        }

        // 渲染群组列表
        function renderGroupsList() {
            groupsList.innerHTML = '';

            // 过滤出当前用户加入的群组
            const userGroups = state.groups.filter(group =>
                group.members.includes(state.currentUser.username)
            );

            if (userGroups.length === 0) {
                groupsList.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-users"></i>
                        <p>尚未加入任何群组</p>
                    </div>
                `;
                return;
            }

            userGroups.forEach(group => {
                const groupElement = document.createElement('div');
                groupElement.className = `group-item ${state.currentGroupId === group.id ? 'active' : ''}`;
                groupElement.dataset.id = group.id;

                groupElement.innerHTML = `
                    <div class="group-avatar">${group.avatar}</div>
                    <div class="group-info">
                        <div class="group-name">
                            <span>${group.name}</span>
                            <span class="group-time">${group.lastMessageTime}</span>
                        </div>
                        <div class="group-last-message">${group.lastMessage}</div>
                    </div>
                    ${group.unreadCount > 0 ? `<div class="unread-count">${group.unreadCount}</div>` : ''}
                `;

                groupElement.addEventListener('click', () => {
                    selectGroup(group.id);

                    // 在移动端选择群组后隐藏侧边栏
                    if (window.innerWidth <= 768) {
                        sidebar.style.left = '-100%';
                    }
                });

                groupsList.appendChild(groupElement);
            });
        }

        // 选择群组
        function selectGroup(groupId) {
            state.currentGroupId = groupId;
            renderGroupsList();
            renderChatMessages(groupId);
        }

        // 渲染聊天消息
        function renderChatMessages(groupId) {
            chatMessages.innerHTML = '';

            if (!groupId) {
                noChatSelected.style.display = 'flex';
                shareResourceBtn.style.display = 'none';
                groupInfoBtn.style.display = 'none';
                leaveGroupBtn.style.display = 'none';
                messageInput.disabled = true;
                sendButton.disabled = true;
                return;
            }

            noChatSelected.style.display = 'none';

            const messages = state.messages[groupId] || [];
            const group = state.groups.find(g => g.id === groupId);

            if (group) {
                currentChatAvatar.textContent = group.avatar;
                currentChatName.textContent = group.name;
                currentChatMembers.textContent = `${group.members.length} 名成员`;
                shareResourceBtn.style.display = 'block';
                groupInfoBtn.style.display = 'block';
                leaveGroupBtn.style.display = 'block';

                // 启用输入框
                messageInput.disabled = false;
                sendButton.disabled = false;
            }

            if (messages.length === 0) {
                chatMessages.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-comments"></i>
                        <p>该群组尚无消息</p>
                    </div>
                `;
                return;
            }

            messages.forEach(message => {
                const messageElement = document.createElement('div');
                const isCurrentUser = message.sender === state.currentUser.username;

                messageElement.className = `message ${isCurrentUser ? 'message-outgoing' : 'message-incoming'}`;

                let messageContent = '';

                if (message.type === 'text') {
                    messageContent = `<div class="message-content">${message.content}</div>`;
                } else if (message.type === 'system') {
                    messageContent = `
                        <div class="message-content" style="background-color: transparent; text-align: center; color: var(--text-color); opacity: 0.7;">
                            <em>${message.content}</em>
                        </div>
                    `;
                } else {
                    // 资源消息
                    let statusBadge = '';
                    if (message.status) {
                        let statusText = '';
                        let statusClass = '';

                        if (message.status === 'pending') {
                            statusText = '等待审核';
                            statusClass = 'status-pending';
                        } else if (message.status === 'approved') {
                            statusText = '已通过';
                            statusClass = 'status-approved';
                        } else if (message.status === 'rejected') {
                            statusText = '未通过';
                            statusClass = 'status-rejected';
                        }

                        statusBadge = `<span class="resource-status ${statusClass}">${statusText}</span>`;
                    }

                    let resourceIcon = '';
                    if (message.type === 'baidu') {
                        resourceIcon = '<i class="fas fa-cloud resource-icon"></i>';
                    } else if (message.type === 'ali') {
                        resourceIcon = '<i class="fas fa-database resource-icon"></i>';
                    } else if (message.type === 'image') {
                        resourceIcon = '<i class="fas fa-image resource-icon"></i>';
                    } else if (message.type === 'audio') {
                        resourceIcon = '<i class="fas fa-music resource-icon"></i>';
                    } else if (message.type === 'video') {
                        resourceIcon = '<i class="fas fa-video resource-icon"></i>';
                    } else {
                        resourceIcon = '<i class="fas fa-link resource-icon"></i>';
                    }

                    // 检查是否为当前用户发送的资源或用户是管理员
                    const canViewResource = isCurrentUser ||
                        state.currentUser.isAdmin ||
                        message.status === 'approved';

                    messageContent = `
                        <div class="message-content">
                            <div>${message.sender} 分享了资源 ${statusBadge}</div>
                            <div class="resource-card">
                                <div class="resource-header">
                                    ${resourceIcon}
                                    <span class="resource-title">${message.description || '未命名资源'}</span>
                                </div>
                                <div class="resource-description">${canViewResource ? message.content : '资源等待审核中...'}</div>
                                ${canViewResource ? `<a href="${message.content}" target="_blank" class="resource-link">查看资源</a>` : ''}
                            </div>
                        </div>
                    `;
                }

                messageElement.innerHTML = `
                    ${messageContent}
                    <div class="message-time">${message.sender !== 'system' ? message.sender + ' · ' : ''}${message.time}</div>
                `;

                chatMessages.appendChild(messageElement);
            });

            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 发送消息
        function sendMessage() {
            const content = messageInput.value.trim();
            if (!content || !state.currentGroupId) return;

            // 检查是否是搜索命令
            if (content.startsWith('/搜索 ')) {
                const keyword = content.substring(3).trim();
                searchResources(keyword);
                messageInput.value = '';
                return;
            }

            // 创建新消息
            const newMessage = {
                id: Date.now(),
                sender: state.currentUser.username,
                content: content,
                time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                type: 'text'
            };

            // 添加到消息列表
            if (!state.messages[state.currentGroupId]) {
                state.messages[state.currentGroupId] = [];
            }
            state.messages[state.currentGroupId].push(newMessage);

            // 更新群组的最后消息
            const groupIndex = state.groups.findIndex(g => g.id === state.currentGroupId);
            if (groupIndex !== -1) {
                state.groups[groupIndex].lastMessage = content.length > 30 ? content.substring(0, 30) + '...' : content;
                state.groups[groupIndex].lastMessageTime = "刚刚";

                // 增加未读消息数（对于其他用户）
                state.groups.forEach((group, index) => {
                    if (group.id === state.currentGroupId && index !== groupIndex) {
                        group.unreadCount += 1;
                    }
                });
            }

            // 保存并更新UI
            saveData();
            renderChatMessages(state.currentGroupId);
            renderGroupsList();

            // 清空输入框
            messageInput.value = '';
        }

        // 搜索资源
        function searchResources(keyword) {
            if (!keyword) return;

            const results = [];
            const lowerKeyword = keyword.toLowerCase();

            // 搜索当前群组的资源消息
            if (state.currentGroupId && state.messages[state.currentGroupId]) {
                state.messages[state.currentGroupId].forEach(message => {
                    if ((message.type !== 'text' && message.type !== 'system') &&
                        (message.content.toLowerCase().includes(lowerKeyword) ||
                            (message.description && message.description.toLowerCase().includes(lowerKeyword)))) {
                        results.push({
                            type: 'resource',
                            id: message.id,
                            content: message.content,
                            description: message.description,
                            time: message.time,
                            status: message.status,
                            sender: message.sender
                        });
                    }
                });
            }

            // 显示搜索结果
            if (results.length > 0) {
                const resultElement = document.createElement('div');
                resultElement.innerHTML = `
                    <div class="message system-message">
                        <div class="message-content" style="background-color: transparent; text-align: center;">
                            <em>找到 ${results.length} 个相关资源</em>
                        </div>
                    </div>
                `;
                chatMessages.appendChild(resultElement);

                results.forEach(result => {
                    const canViewResource = result.sender === state.currentUser.username ||
                        state.currentUser.isAdmin ||
                        result.status === 'approved';

                    const resultElement = document.createElement('div');
                    resultElement.className = 'message message-incoming';

                    let resourceIcon = '';
                    if (result.type === 'baidu') {
                        resourceIcon = '<i class="fas fa-cloud resource-icon"></i>';
                    } else if (result.type === 'ali') {
                        resourceIcon = '<i class="fas fa-database resource-icon"></i>';
                    } else {
                        resourceIcon = '<i class="fas fa-link resource-icon"></i>';
                    }

                    resultElement.innerHTML = `
                        <div class="message-content">
                            <div class="resource-card">
                                <div class="resource-header">
                                    ${resourceIcon}
                                    <span class="resource-title">搜索结果: ${result.description || '未命名资源'}</span>
                                </div>
                                <div class="resource-description">${canViewResource ? result.content : '资源等待审核中...'}</div>
                                ${canViewResource ? `<a href="${result.content}" target="_blank" class="resource-link">查看资源</a>` : ''}
                            </div>
                        </div>
                        <div class="message-time">${result.time}</div>
                    `;

                    chatMessages.appendChild(resultElement);
                });

                // 滚动到底部
                chatMessages.scrollTop = chatMessages.scrollHeight;
            } else {
                const noResultElement = document.createElement('div');
                noResultElement.innerHTML = `
                    <div class="message system-message">
                        <div class="message-content" style="background-color: transparent; text-align: center;">
                            <em>未找到相关资源</em>
                        </div>
                    </div>
                `;
                chatMessages.appendChild(noResultElement);

                // 滚动到底部
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        }

        // 搜索群组和资源
        function performSearch(keyword) {
            if (!keyword) {
                searchResults.style.display = 'none';
                return;
            }

            const lowerKeyword = keyword.toLowerCase();
            const results = [];

            // 搜索群组
            state.groups.forEach(group => {
                if (group.name.toLowerCase().includes(lowerKeyword) ||
                    group.description.toLowerCase().includes(lowerKeyword)) {
                    results.push({
                        type: 'group',
                        id: group.id,
                        name: group.name,
                        description: group.description,
                        isMember: group.members.includes(state.currentUser.username)
                    });
                }
            });

            // 搜索资源（在所有群组中）
            Object.keys(state.messages).forEach(groupId => {
                const group = state.groups.find(g => g.id == groupId);
                if (group && group.members.includes(state.currentUser.username)) {
                    state.messages[groupId].forEach(message => {
                        if ((message.type !== 'text' && message.type !== 'system') &&
                            (message.content.toLowerCase().includes(lowerKeyword) ||
                                (message.description && message.description.toLowerCase().includes(lowerKeyword)))) {
                            results.push({
                                type: 'resource',
                                id: message.id,
                                content: message.content,
                                description: message.description,
                                groupId: groupId,
                                groupName: group.name,
                                status: message.status
                            });
                        }
                    });
                }
            });

            // 显示搜索结果
            displaySearchResults(results);
        }

        // 显示搜索结果
        function displaySearchResults(results) {
            searchResults.innerHTML = '';

            if (results.length === 0) {
                searchResults.innerHTML = '<div class="empty-state">未找到相关结果</div>';
                searchResults.style.display = 'block';
                return;
            }

            results.forEach(result => {
                const resultElement = document.createElement('div');
                resultElement.className = 'search-result-item';

                if (result.type === 'group') {
                    resultElement.innerHTML = `
                        <i class="fas fa-users"></i>
                        <div style="flex: 1;">
                            <div style="font-weight: 600;">${result.name}</div>
                            <div style="font-size: 13px; opacity: 0.7;">${result.description}</div>
                        </div>
                        ${result.isMember ?
                            '<span style="font-size: 12px; opacity: 0.7;">已加入</span>' :
                            '<button class="join-group-btn" data-id="' + result.id + '">加入群组</button>'
                        }
                    `;

                    resultElement.addEventListener('click', () => {
                        if (result.isMember) {
                            selectGroup(result.id);
                            searchResults.style.display = 'none';
                            searchInput.value = '';
                        }
                    });

                    // 为加入群组按钮添加事件
                    const joinBtn = resultElement.querySelector('.join-group-btn');
                    if (joinBtn) {
                        joinBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            joinGroup(result.id);
                            searchResults.style.display = 'none';
                            searchInput.value = '';
                        });
                    }
                } else if (result.type === 'resource') {
                    const canViewResource = state.currentUser.isAdmin || result.status === 'approved';

                    resultElement.innerHTML = `
                        <i class="fas fa-link"></i>
                        <div style="flex: 1;">
                            <div class="search-resource-title">${result.description || '未命名资源'}</div>
                            <div class="search-resource-content">${canViewResource ? result.content : '资源等待审核中...'}</div>
                            <div class="search-resource-group">来自: ${result.groupName}</div>
                        </div>
                    `;

                    resultElement.addEventListener('click', () => {
                        selectGroup(result.groupId);
                        searchResults.style.display = 'none';
                        searchInput.value = '';
                    });
                }

                searchResults.appendChild(resultElement);
            });

            searchResults.style.display = 'block';
        }

        // 加入群组
        function joinGroup(groupId) {
            const groupIndex = state.groups.findIndex(g => g.id === groupId);
            if (groupIndex !== -1 && !state.groups[groupIndex].members.includes(state.currentUser.username)) {
                state.groups[groupIndex].members.push(state.currentUser.username);

                // 添加系统消息
                if (!state.messages[groupId]) {
                    state.messages[groupId] = [];
                }

                state.messages[groupId].push({
                    id: Date.now(),
                    sender: 'system',
                    content: `${state.currentUser.username} 加入了群组`,
                    time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                    type: 'system'
                });

                saveData();
                renderGroupsList();
                selectGroup(groupId);

                alert('已成功加入群组');
            }
        }

        // 退出群组
        function leaveGroup() {
            if (!state.currentGroupId) return;

            const groupIndex = state.groups.findIndex(g => g.id === state.currentGroupId);
            if (groupIndex !== -1) {
                const memberIndex = state.groups[groupIndex].members.indexOf(state.currentUser.username);
                if (memberIndex !== -1) {
                    state.groups[groupIndex].members.splice(memberIndex, 1);

                    // 添加系统消息
                    state.messages[state.currentGroupId].push({
                        id: Date.now(),
                        sender: 'system',
                        content: `${state.currentUser.username} 退出了群组`,
                        time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                        type: 'system'
                    });

                    saveData();

                    // 如果用户是群组创建者且群组中没有其他成员，删除群组
                    if (state.groups[groupIndex].creator === state.currentUser.username && state.groups[groupIndex].members.length === 0) {
                        state.groups.splice(groupIndex, 1);
                        delete state.messages[state.currentGroupId];
                    }

                    state.currentGroupId = null;
                    renderGroupsList();
                    renderChatMessages(null);

                    alert('已成功退出群组');
                }
            }
        }

        // 创建新群组
        function createGroup() {
            const name = document.getElementById('group-name').value.trim();
            const description = document.getElementById('group-description').value.trim();

            if (!name) {
                alert('请输入群组名称');
                return;
            }

            const newGroup = {
                id: Date.now(),
                name: name,
                avatar: name.charAt(0).toUpperCase(),
                description: description,
                creator: state.currentUser.username,
                members: [state.currentUser.username],
                lastMessage: '群组已创建',
                lastMessageTime: '刚刚',
                unreadCount: 0
            };

            state.groups.push(newGroup);
            state.messages[newGroup.id] = [{
                id: Date.now(),
                sender: 'system',
                content: `群组 "${name}" 已创建`,
                time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                type: 'system'
            }];

            saveData();
            hideModal(createGroupModal);
            renderGroupsList();
            selectGroup(newGroup.id);

            // 清空表单
            document.getElementById('group-name').value = '';
            document.getElementById('group-description').value = '';
        }

        // 分享资源
        function shareResource() {
            const type = document.getElementById('resource-type').value;
            const content = document.getElementById('resource-content').value.trim();
            const description = document.getElementById('resource-description').value.trim();

            if (!content) {
                alert('请输入资源内容');
                return;
            }

            if (!state.currentGroupId) {
                alert('请先选择群组');
                return;
            }

            const newMessage = {
                id: Date.now(),
                sender: state.currentUser.username,
                content: content,
                description: description,
                time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                type: type,
                status: state.currentUser.isAdmin ? 'approved' : 'pending'
            };

            if (!state.messages[state.currentGroupId]) {
                state.messages[state.currentGroupId] = [];
            }

            state.messages[state.currentGroupId].push(newMessage);

            if (userGroups.length === 0) {
                const emptyState = document.createElement('div');
                emptyState.className = 'empty-state';
                emptyState.innerHTML = `
                    <i class="fas fa-search"></i>
                    <p>你还没有加入任何群组</p>
                    <p>使用搜索功能查找并加入群组</p>
                `;
                groupsList.appendChild(emptyState);
            } else {
                userGroups.forEach(group => {
                    const groupItem = document.createElement('div');
                    groupItem.className = `group-item ${state.currentGroupId === group.id ? 'active' : ''}`;
                    groupItem.dataset.groupId = group.id;

                    groupItem.innerHTML = `
                        <div class="group-avatar">${group.avatar}</div>
                        <div class="group-info">
                            <div class="group-name">
                                ${group.name}
                                <span class="group-time">${group.lastMessageTime}</span>
                            </div>
                            <div class="group-last-message">${group.lastMessage}</div>
                        </div>
                        ${group.unreadCount > 0 ? `<div class="unread-count">${group.unreadCount}</div>` : ''}
                    `;

                    groupItem.addEventListener('click', () => {
                        selectGroup(group.id);

                        // 在移动端点击群组后隐藏侧边栏
                        if (window.innerWidth <= 768) {
                            sidebar.classList.remove('active');
                        }
                    });

                    groupsList.appendChild(groupItem);
                });
            }
        }

        // 选择群组
        function selectGroup(groupId) {
            state.currentGroupId = groupId;
            const group = state.groups.find(g => g.id === groupId);

            if (group) {
                currentChatAvatar.textContent = group.avatar;
                currentChatName.textContent = group.name;
                currentChatMembers.textContent = `${group.members.length} 名成员`;

                // 显示聊天操作按钮
                shareResourceBtn.style.display = 'block';
                groupInfoBtn.style.display = 'block';
                leaveGroupBtn.style.display = 'block';

                // 启用输入框和发送按钮
                messageInput.disabled = false;
                sendButton.disabled = false;

                // 隐藏无选择提示
                noChatSelected.style.display = 'none';

                // 渲染消息
                renderMessages(groupId);

                // 重置未读计数
                resetUnreadCount(groupId);

                // 更新群组列表
                renderGroupsList();
            }
        }

        // 渲染消息
        function renderMessages(groupId) {
            chatMessages.innerHTML = '';

            if (!state.messages[groupId]) {
                return;
            }

            state.messages[groupId].forEach(message => {
                const messageEl = document.createElement('div');
                messageEl.className = `message ${message.sender === state.currentUser.username ? 'message-outgoing' : 'message-incoming'}`;

                let messageContent = '';

                if (message.type === 'text') {
                    messageContent = message.content;
                } else if (['baidu', 'ali', 'other', 'image', 'audio', 'video'].includes(message.type)) {
                    const typeNames = {
                        'baidu': '百度网盘',
                        'ali': '阿里云盘',
                        'other': '其他网盘',
                        'image': '图片',
                        'audio': '音频',
                        'video': '视频'
                    };

                    messageContent = `
                        <div class="resource-card">
                            <div class="resource-header">
                                <i class="fas ${getIconForResourceType(message.type)} resource-icon"></i>
                                <span class="resource-title">${typeNames[message.type]}资源</span>
                                ${message.status ? `<span class="resource-status status-${message.status}">${getStatusText(message.status)}</span>` : ''}
                            </div>
                            <div class="resource-description">${message.description || '无描述'}</div>
                            <a href="${message.type === 'text' ? '#' : message.content}" target="_blank" class="resource-link">
                                ${message.type === 'text' ? '查看内容' : '访问资源'}
                            </a>
                        </div>
                    `;
                } else if (message.type === 'system') {
                    messageContent = `<em>${message.content}</em>`;
                }

                messageEl.innerHTML = `
                    <div class="message-content">
                        ${message.sender !== 'system' ? `<strong>${message.sender}:</strong> ` : ''}
                        ${messageContent}
                    </div>
                    <div class="message-time">${message.time}</div>
                `;

                chatMessages.appendChild(messageEl);
            });

            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 获取资源类型对应的图标
        function getIconForResourceType(type) {
            const icons = {
                'baidu': 'fa-cloud',
                'ali': 'fa-cloud',
                'other': 'fa-cloud',
                'image': 'fa-image',
                'audio': 'fa-music',
                'video': 'fa-video'
            };
            return icons[type] || 'fa-file';
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusTexts = {
                'pending': '待审核',
                'approved': '已通过',
                'rejected': '已拒绝'
            };
            return statusTexts[status] || '';
        }

        // 重置未读计数
        function resetUnreadCount(groupId) {
            const group = state.groups.find(g => g.id === groupId);
            if (group) {
                group.unreadCount = 0;
                saveData();
            }
        }

        // 发送消息
        function sendMessage() {
            const content = messageInput.value.trim();

            if (!content || !state.currentGroupId) {
                return;
            }

            // 检查是否是搜索命令
            if (content.startsWith('/搜索')) {
                const keyword = content.substring(3).trim();
                searchResourcesInGroup(keyword);
                messageInput.value = '';
                return;
            }

            // 创建文本消息
            const message = {
                id: Date.now(),
                sender: state.currentUser.username,
                content: content,
                time: getCurrentTime(),
                type: 'text'
            };

            // 添加到消息列表
            if (!state.messages[state.currentGroupId]) {
                state.messages[state.currentGroupId] = [];
            }

            state.messages[state.currentGroupId].push(message);

            // 更新群组最后一条消息
            const group = state.groups.find(g => g.id === state.currentGroupId);
            if (group) {
                group.lastMessage = content;
                group.lastMessageTime = getCurrentTime();
            }

            // 保存并重新渲染
            saveData();
            renderMessages(state.currentGroupId);
            renderGroupsList();

            // 清空输入框
            messageInput.value = '';
        }

        // 获取当前时间
        function getCurrentTime() {
            const now = new Date();
            return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
        }

        // 在群组中搜索资源
        function searchResourcesInGroup(keyword) {
            if (!state.currentGroupId || !keyword) {
                return;
            }

            const group = state.groups.find(g => g.id === state.currentGroupId);
            if (!group) {
                return;
            }

            const messages = state.messages[state.currentGroupId] || [];
            const results = messages.filter(message => {
                // 只搜索已审核通过的资源
                if (message.type !== 'text' && message.status !== 'approved') {
                    return false;
                }

                // 搜索内容或描述中包含关键字
                const contentMatch = message.content && message.content.includes(keyword);
                const descriptionMatch = message.description && message.description.includes(keyword);

                return contentMatch || descriptionMatch;
            });

            // 显示搜索结果
            chatMessages.innerHTML = '';

            if (results.length === 0) {
                const noResults = document.createElement('div');
                noResults.className = 'empty-state';
                noResults.innerHTML = `
                    <i class="fas fa-search"></i>
                    <p>没有找到与"${keyword}"相关的资源</p>
                `;
                chatMessages.appendChild(noResults);
            } else {
                const resultsHeader = document.createElement('div');
                resultsHeader.className = 'message-incoming';
                resultsHeader.innerHTML = `
                    <div class="message-content">
                        <strong>搜索结果:</strong> 找到 ${results.length} 个与"${keyword}"相关的资源
                    </div>
                `;
                chatMessages.appendChild(resultsHeader);

                results.forEach(message => {
                    const messageEl = document.createElement('div');
                    messageEl.className = `message ${message.sender === state.currentUser.username ? 'message-outgoing' : 'message-incoming'}`;

                    let messageContent = '';

                    if (message.type === 'text') {
                        messageContent = message.content;
                    } else {
                        const typeNames = {
                            'baidu': '百度网盘',
                            'ali': '阿里云盘',
                            'other': '其他网盘',
                            'image': '图片',
                            'audio': '音频',
                            'video': '视频'
                        };

                        messageContent = `
                            <div class="resource-card">
                                <div class="resource-header">
                                    <i class="fas ${getIconForResourceType(message.type)} resource-icon"></i>
                                    <span class="resource-title">${typeNames[message.type]}资源</span>
                                </div>
                                <div class="resource-description">${message.description || '无描述'}</div>
                                <a href="${message.content}" target="_blank" class="resource-link">访问资源</a>
                            </div>
                        `;
                    }

                    messageEl.innerHTML = `
                        <div class="message-content">
                            <strong>${message.sender}:</strong>
                            ${messageContent}
                        </div>
                        <div class="message-time">${message.time}</div>
                    `;

                    chatMessages.appendChild(messageEl);
                });
            }
        }

        // 搜索群组或资源
        function search(query) {
            if (!query) {
                searchResults.style.display = 'none';
                return;
            }

            query = query.toLowerCase();

            // 搜索群组
            const groupResults = state.groups.filter(group =>
                group.name.toLowerCase().includes(query) ||
                group.description.toLowerCase().includes(query)
            );

            // 搜索资源（只搜索已审核的）
            const resourceResults = [];
            Object.keys(state.messages).forEach(groupId => {
                const group = state.groups.find(g => g.id === parseInt(groupId));
                if (!group) return;

                (state.messages[groupId] || []).forEach(message => {
                    if (message.status === 'approved' &&
                        (message.type !== 'text' && message.type !== 'system') &&
                        (message.content.toLowerCase().includes(query) ||
                            (message.description && message.description.toLowerCase().includes(query)))) {

                        resourceResults.push({
                            ...message,
                            groupId: parseInt(groupId),
                            groupName: group.name
                        });
                    }
                });
            });

            // 显示搜索结果
            searchResults.innerHTML = '';
            searchResults.style.display = 'block';

            if (groupResults.length === 0 && resourceResults.length === 0) {
                const noResults = document.createElement('div');
                noResults.className = 'empty-state';
                noResults.innerHTML = `
                    <i class="fas fa-search"></i>
                    <p>没有找到与"${query}"相关的内容</p>
                `;
                searchResults.appendChild(noResults);
                return;
            }

            // 添加群组结果
            if (groupResults.length > 0) {
                const groupHeader = document.createElement('div');
                groupHeader.style.padding = '8px 15px';
                groupHeader.style.fontWeight = '600';
                groupHeader.style.borderBottom = '1px solid var(--border-color)';
                groupHeader.textContent = '群组';
                searchResults.appendChild(groupHeader);

                groupResults.forEach(group => {
                    const isMember = group.members.includes(state.currentUser.username);

                    const resultItem = document.createElement('div');
                    resultItem.className = 'search-result-item';
                    resultItem.innerHTML = `
                        <i class="fas fa-users"></i>
                        <div style="flex: 1;">
                            <div style="font-weight: 500;">${group.name}</div>
                            <div style="font-size: 12px; opacity: 0.7;">${group.description}</div>
                        </div>
                        ${!isMember ? `<button class="join-group-btn" data-group-id="${group.id}">加入</button>` : ''}
                    `;

                    resultItem.addEventListener('click', (e) => {
                        // 如果点击的是加入按钮，不触发选择群组
                        if (!e.target.closest('.join-group-btn')) {
                            selectGroup(group.id);
                            searchResults.style.display = 'none';
                            searchInput.value = '';

                            // 在移动端选择群组后隐藏侧边栏
                            if (window.innerWidth <= 768) {
                                sidebar.classList.remove('active');
                            }
                        }
                    });

                    searchResults.appendChild(resultItem);
                });
            }

            // 添加资源结果
            if (resourceResults.length > 0) {
                const resourceHeader = document.createElement('div');
                resourceHeader.style.padding = '8px 15px';
                resourceHeader.style.fontWeight = '600';
                resourceHeader.style.borderBottom = '1px solid var(--border-color)';
                resourceHeader.textContent = '资源';
                searchResults.appendChild(resourceHeader);

                resourceResults.forEach(resource => {
                    const resultItem = document.createElement('div');
                    resultItem.className = 'search-resource-item';

                    const typeNames = {
                        'baidu': '百度网盘',
                        'ali': '阿里云盘',
                        'other': '其他网盘',
                        'image': '图片',
                        'audio': '音频',
                        'video': '视频'
                    };

                    resultItem.innerHTML = `
                        <div class="search-resource-title">
                            <i class="fas ${getIconForResourceType(resource.type)}" style="margin-right: 5px;"></i>
                            ${typeNames[resource.type]}资源
                        </div>
                        <div class="search-resource-content">${resource.description || resource.content}</div>
                        <div class="search-resource-group">来自群组: ${resource.groupName}</div>
                    `;

                    resultItem.addEventListener('click', () => {
                        // 切换到资源所在的群组
                        selectGroup(resource.groupId);
                        searchResults.style.display = 'none';
                        searchInput.value = '';

                        // 在移动端选择群组后隐藏侧边栏
                        if (window.innerWidth <= 768) {
                            sidebar.classList.remove('active');
                        }
                    });

                    searchResults.appendChild(resultItem);
                });
            }
        }

        // 加入群组
        function joinGroup(groupId) {
            const group = state.groups.find(g => g.id === groupId);

            if (group && !group.members.includes(state.currentUser.username)) {
                group.members.push(state.currentUser.username);
                group.unreadCount = 1; // 加入后有一条系统消息提示

                // 添加系统消息
                if (!state.messages[groupId]) {
                    state.messages[groupId] = [];
                }

                state.messages[groupId].push({
                    id: Date.now(),
                    sender: 'system',
                    content: `${state.currentUser.username} 加入了群组`,
                    time: getCurrentTime(),
                    type: 'system'
                });

                saveData();
                renderGroupsList();
                searchResults.style.display = 'none';
                searchInput.value = '';
            }
        }

        // 创建群组
        function createGroup(name, description) {
            if (!name) {
                alert('请输入群组名称');
                return;
            }

            const newGroupId = state.groups.length > 0
                ? Math.max(...state.groups.map(g => g.id)) + 1
                : 1;

            const newGroup = {
                id: newGroupId,
                name: name,
                avatar: name.charAt(0).toUpperCase(),
                description: description || '',
                creator: state.currentUser.username,
                members: [state.currentUser.username],
                lastMessage: '群组创建成功',
                lastMessageTime: getCurrentTime(),
                unreadCount: 0
            };

            state.groups.push(newGroup);

            // 添加系统消息
            state.messages[newGroupId] = [{
                id: Date.now(),
                sender: 'system',
                content: `群组 "${name}" 创建成功，欢迎加入！`,
                time: getCurrentTime(),
                type: 'system'
            }];

            saveData();
            renderGroupsList();
            selectGroup(newGroupId);

            // 关闭模态框
            createGroupModal.style.display = 'none';
        }

        // 分享资源
        function shareResource(type, content, description) {
            if (!content || !state.currentGroupId) {
                alert('请输入资源内容');
                return;
            }

            // 检查是否为管理员
            const isAdmin = state.currentUser && state.currentUser.isAdmin;

            // 创建资源消息
            const message = {
                id: Date.now(),
                sender: state.currentUser.username,
                content: content,
                description: description || '',
                time: getCurrentTime(),
                type: type,
                // 管理员发布的资源自动通过审核
                status: isAdmin ? 'approved' : 'pending'
            };

            // 添加到消息列表
            if (!state.messages[state.currentGroupId]) {
                state.messages[state.currentGroupId] = [];
            }

            state.messages[state.currentGroupId].push(message);

            // 添加系统消息
            if (!isAdmin) {
                state.messages[state.currentGroupId].push({
                    id: Date.now() + 1,
                    sender: 'system',
                    content: '资源等待管理员审核',
                    time: getCurrentTime(),
                    type: 'system'
                });
            }

            // 更新群组最后一条消息
            const group = state.groups.find(g => g.id === state.currentGroupId);
            if (group) {
                group.lastMessage = `分享了${type === 'baidu' ? '百度网盘' :
                    type === 'ali' ? '阿里云盘' : '资源'}`;
                group.lastMessageTime = getCurrentTime();
            }

            // 通知所有群组成员（增加未读计数）
            state.groups.forEach(g => {
                if (g.id === state.currentGroupId) return;

                const group = state.groups.find(gr => gr.id === state.currentGroupId);
                if (group && group.members.includes(g.creator) && g.creator !== state.currentUser.username) {
                    g.unreadCount = (g.unreadCount || 0) + 1;
                }
            });

            saveData();
            renderMessages(state.currentGroupId);
            renderGroupsList();

            // 关闭模态框
            shareResourceModal.style.display = 'none';
        }

        // 显示群组信息
        function showGroupInfo() {
            if (!state.currentGroupId) return;

            const group = state.groups.find(g => g.id === state.currentGroupId);
            if (!group) return;

            document.getElementById('group-info-title').textContent = `${group.name} 信息`;
            document.getElementById('info-group-name').textContent = group.name;
            document.getElementById('info-group-description').textContent = group.description || '无描述';
            document.getElementById('info-group-creator').textContent = group.creator;

            // 显示成员列表
            const membersList = document.getElementById('info-group-members');
            membersList.innerHTML = '';

            group.members.forEach(member => {
                const memberEl = document.createElement('div');
                memberEl.style.padding = '4px 0';
                memberEl.innerHTML = `
                    <i class="fas fa-user" style="margin-right: 8px; opacity: 0.7;"></i>
                    ${member} ${member === group.creator ? '<span style="font-size: 11px; background-color: var(--primary-color); color: white; padding: 1px 6px; border-radius: 10px;">创建者</span>' : ''}
                `;
                membersList.appendChild(memberEl);
            });

            groupInfoModal.style.display = 'flex';
        }

        // 退出群组
        function leaveGroup() {
            if (!state.currentGroupId) return;

            const group = state.groups.find(g => g.id === state.currentGroupId);
            if (!group) return;

            // 不能退出自己创建的群组
            if (group.creator === state.currentUser.username) {
                alert('您是群组创建者，不能退出群组');
                return;
            }

            if (confirm(`确定要退出 "${group.name}" 吗？`)) {
                // 移除成员
                group.members = group.members.filter(member => member !== state.currentUser.username);

                // 添加系统消息
                if (state.messages[state.currentGroupId]) {
                    state.messages[state.currentGroupId].push({
                        id: Date.now(),
                        sender: 'system',
                        content: `${state.currentUser.username} 退出了群组`,
                        time: getCurrentTime(),
                        type: 'system'
                    });
                }

                // 重置当前群组
                state.currentGroupId = null;

                saveData();
                renderGroupsList();

                // 重置聊天界面
                currentChatAvatar.textContent = 'G';
                currentChatName.textContent = '网盘资源共享社区';
                currentChatMembers.textContent = '选择一个群组开始聊天';
                shareResourceBtn.style.display = 'none';
                groupInfoBtn.style.display = 'none';
                leaveGroupBtn.style.display = 'none';
                messageInput.disabled = true;
                sendButton.disabled = true;
                chatMessages.innerHTML = '';
                noChatSelected.style.display = 'flex';
            }
        }

        // 登录
        function login(username, password) {
            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }

            const user = state.users.find(u => u.username === username && u.password === password);

            if (user) {
                localStorage.setItem('current-user', JSON.stringify(user));
                state.currentUser = user;
                updateUserInterface();
                renderGroupsList();
                loginModal.style.display = 'none';
            } else {
                alert('用户名或密码错误');
            }
        }

        // 注册
        function register(username, password, confirmPassword) {
            if (!username || !password || !confirmPassword) {
                alert('请填写所有字段');
                return;
            }

            if (password !== confirmPassword) {
                alert('两次密码输入不一致');
                return;
            }

            if (state.users.some(u => u.username === username)) {
                alert('用户名已存在');
                return;
            }

            const newUser = {
                username: username,
                password: password,
                isAdmin: false
            };

            state.users.push(newUser);
            saveData();

            alert('注册成功，请登录');
            registerModal.style.display = 'none';
            loginModal.style.display = 'flex';
        }

        // 显示登录模态框
        function showLoginModal() {
            loginModal.style.display = 'flex';
            registerModal.style.display = 'none';
        }

        // 显示注册模态框
        function showRegisterModal() {
            registerModal.style.display = 'flex';
            loginModal.style.display = 'none';
        }

        // 设置事件监听器
        function setupEventListeners() {
            // 主题切换
            themeToggle.addEventListener('click', () => {
                const isDark = document.body.getAttribute('data-theme') === 'dark';
                if (isDark) {
                    document.body.removeAttribute('data-theme');
                    themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
                } else {
                    document.body.setAttribute('data-theme', 'dark');
                    themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
                }
            });

            // 搜索
            searchInput.addEventListener('input', (e) => {
                search(e.target.value);
            });

            // 点击页面其他地方关闭搜索结果
            document.addEventListener('click', (e) => {
                if (!e.target.closest('.search-container')) {
                    searchResults.style.display = 'none';
                }
            });

            // 发送消息
            sendButton.addEventListener('click', sendMessage);
            messageInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    sendMessage();
                }
            });

            // 移动端菜单按钮
            mobileMenuBtn.addEventListener('click', () => {
                sidebar.classList.toggle('active');
            });

            // 创建群组按钮
            createGroupBtn.addEventListener('click', () => {
                createGroupModal.style.display = 'flex';
            });

            // 分享资源按钮
            shareResourceBtn.addEventListener('click', () => {
                shareResourceModal.style.display = 'flex';
            });

            // 群组信息按钮
            groupInfoBtn.addEventListener('click', showGroupInfo);

            // 退出群组按钮
            leaveGroupBtn.addEventListener('click', leaveGroup);

            // 模态框关闭按钮
            document.querySelectorAll('.close-modal').forEach(btn => {
                btn.addEventListener('click', function () {
                    this.closest('.modal').style.display = 'none';
                });
            });

            // 点击模态框外部关闭
            window.addEventListener('click', (e) => {
                if (e.target.classList.contains('modal')) {
                    e.target.style.display = 'none';
                }
            });

            // 登录/注册相关
            document.getElementById('show-register-btn').addEventListener('click', showRegisterModal);
            document.getElementById('show-login-btn').addEventListener('click', showLoginModal);
            document.getElementById('do-login-btn').addEventListener('click', () => {
                const username = document.getElementById('login-username').value;
                const password = document.getElementById('login-password').value;
                login(username, password);
            });
            document.getElementById('do-register-btn').addEventListener('click', () => {
                const username = document.getElementById('register-username').value;
                const password = document.getElementById('register-password').value;
                const confirmPassword = document.getElementById('register-password-confirm').value;
                register(username, password, confirmPassword);
            });

            // 创建群组
            document.getElementById('do-create-group').addEventListener('click', () => {
                const name = document.getElementById('group-name').value;
                const description = document.getElementById('group-description').value;
                createGroup(name, description);
            });
            document.getElementById('cancel-create-group').addEventListener('click', () => {
                createGroupModal.style.display = 'none';
            });

            // 分享资源
            document.getElementById('do-share-resource').addEventListener('click', () => {
                const type = document.getElementById('resource-type').value;
                const content = document.getElementById('resource-content').value;
                const description = document.getElementById('resource-description').value;
                shareResource(type, content, description);
            });
            document.getElementById('cancel-share-resource').addEventListener('click', () => {
                shareResourceModal.style.display = 'none';
            });

            // 关闭群组信息
            document.getElementById('close-group-info').addEventListener('click', () => {
                groupInfoModal.style.display = 'none';
            });

            // 委托事件处理 - 加入群组按钮
            searchResults.addEventListener('click', (e) => {
                const joinBtn = e.target.closest('.join-group-btn');
                if (joinBtn) {
                    const groupId = parseInt(joinBtn.dataset.groupId);
                    joinGroup(groupId);
                }
            });
        }

        // 初始化应用
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>

</html>